#include <ArduinoJson.h>

const char *configFilename = "/config.txt";  // <- SD library uses 8.3 filenames

StaticJsonDocument<512> doc;  



void setInitConfig(){
  doc["dhtServer"]="http://public.zzzfree.cn/iot/dht.php?l=hc&v=";
  doc["dhtHost"]="public.zzzfree.cn";
  doc["dhtUrl"]="/iot/dht.php";
  doc["dhtQuery"]="l=hc&v=";
  doc["sleepInterval"] = "5000";
  doc["dhtInterval"] = "60000";  // 60s
  doc["isDhtKeepAlive"] = "1";
}



// Saves the configuration to a file
void saveConfiguration() {
  // Delete existing file, otherwise the configuration is appended to the file  

  Serial.println ("Save Configuration..."); 

  if (!LittleFS.begin()) {
    Serial.println ("LittleFS mount failed"); 
  }

 File file = LittleFS.open(configFilename, "w+");
  if (!file) {
    Serial.println("Failed to open config file for writing"); 
    return;
  }
 
  delay(2000); // Make sure the CREATE and LASTWRITE times are different   
 
  if (!file) {
    Serial.println(F("Failed to create file"));
    return;
  }

  // Serialize JSON to file
  if (serializeJson(doc, file) == 0) {
    Serial.println(F("Failed to write to Config.txt file"));
  }

  // Close the file
  file.close();

  LittleFS.end();
}
 


// Loads the configuration from a file
void loadConfiguration() {   

  if (!LittleFS.begin()) {
    Serial.println ("LittleFS mount failed"); 
  }
  
  Serial.println("load Configuration ...");

  File file = LittleFS.open(configFilename, "r");
  if (!file) {
    Serial.println ("Failed to open config file for reading, using default configuration"); 
    setInitConfig();
    saveConfiguration();
    return;
  }  

  // Deserialize the JSON document
  DeserializationError error = deserializeJson(doc, file);  
  
  // Close the file (Curiously, File's destructor doesn't close the file)
  file.close();
  
  LittleFS.end();
  
  if (error){
    Serial.println(F("Failed to read file, using default configuration"));
    deleteFile(configFilename);
    setInitConfig();
    saveConfiguration();
  } 

}